<template>
	<view class="pagebox pd30">
			<view class="label mb10 mt30">照片上传及说明：</view>
			<view class="spacebox pd20 flex-column mb10" v-for="(v,i) in obj.roles">
				<text v-if="v.title" class="spacetitle mb10">• {{v.title}}：</text>
				<view v-if="v.adjure" class="mb10" v-html="`【拍摄要求】：`+v.adjure"></view>
				<template v-if="!obj.f.file_id">
					<text v-if="v.caption" class="mb10">【数量要求】：{{v.caption}}</text>
					<template  v-for="(k,n) in v.forms">
						<view class="mb10" v-if="k.show">
							<view v-if="v.caption" class="mb10">【{{k.key}}】：</view>
							<view v-if="k.type=='select'" class="locations flex-row ju-between">
								<view v-for="(l,m) in k.enums" :key="m" :class="['loca',k.value==l?'locaactive':'']" @click="k.value=l">{{l}}</view>
							</view>
							<textarea v-if="k.type=='text'" class="textarea1" v-model="k.value" :placeholder="`请填写${k.key}`" maxlength="30" style="width: 650rpx;" placeholder-style="color:#c7c8c9;font-size:26rpx;" auto-height/>
						</view>
					</template>
				</template>
				<my-form-upload
					label="【拍摄/上传】："
					:labeldesc="obj.f.file_id>0?'原图预览':''"
					:count="obj.f.file_id>0?1:9"
					v-model="v.filename"
					dir="images" :maxW="1200" type="img"
					@descclick="proxy.$c.previewImages([obj.f.realfilename],0)" />
			</view>
		<template v-if="obj.f.file_id==0">
			<view class="label mb10 mt30">情况标题：</view>
			<textarea class="textarea1" v-model="obj.f.situation" placeholder="请填写施工部位或会议主题或施工杆塔号"  maxlength="20" placeholder-style="color:#c7c8c9;font-size:26rpx;" auto-height/>
			
			<view class="label mb10 mt30">情况说明：</view>
			<textarea v-model="obj.f.caption" placeholder="请填写情况说明"  maxlength="100" placeholder-style="color:#c7c8c9;font-size:26rpx;" auto-height/>
			<view class="label mb10 mt30">水印位置：</view>
			<view class="locations flex-row ju-between">
				<view :class="['loca',obj.f.location==0?'locaactive':'']" @click="obj.f.location=0">左下角</view>
				<view :class="['loca',obj.f.location==1?'locaactive':'']" @click="obj.f.location=1">右下角</view>
			</view>
		</template>
		
		<!-- <my-form-upload v-else label="拍摄/上传照片：" :labeldesc="obj.f.file_id>0?'原图预览':''" v-model="obj.f.filename" dir="images" :count="obj.f.file_id>0?1:9" :maxW="1200" type="img" @descclick="proxy.$c.previewImages([obj.f.realfilename],0)" /> -->
		
		<button class="linebtn mb10" @click="pre">预览</button>
		<button class="btn" @click="submit">提交</button>
		
		<view v-if="obj.showpre==true" class="prebox flex-center flex-column-center" @click="obj.showpre=false">
			<view class="imgbox mb20 overflow-y" @click.stop="()=>{}">
				<image class="img mb10" :id="`preimg_${obj.preidx}`" :src="obj.pres[obj.preidx]" mode="widthFix">
					<view class="shuiyin flex-column pd10" :class="[`pos${obj.f.location}`]" :style="{'transform': `scale(${obj.syScale})`}">
						<image style="width: 100rpx;margin-bottom: 10rpx;" src="../static/logo1.png" mode="widthFix"></image>
						<view class="flex-row mb10">
							<view style="min-width: 106rpx;">工程名称:</view>
							<view class="textline lineTwo">{{obj.f.project_name}}</view>
						</view>
						<view class="flex-row mb10">
							<view style="min-width: 106rpx;">{{obj.f.situation}}:</view>
							<view class="textline lineTwo">{{obj.f.caption}}</view>
						</view>
						<view class="flex-row mb10">
							<view style="min-width: 106rpx;">拍摄日期:</view>
							<view class="textline lineTwo">{{dayjs().format('YYYY-MM-DD')}}</view>
						</view>
					</view>
				</image>
			</view>
			<view class="flex-row-center w100">
				<view class="minibtn" @click.stop="next(-1)">上一张</view>
				<view class="minibtn ml10 mr10" @click.stop="next(1)">下一张</view>
				<view class="minibtn1">关闭</view>
			</view>
		</view>
	</view>
</template>

<script setup>
    import { reactive, getCurrentInstance,onMounted,watch,computed,nextTick } from 'vue'
	import { onLoad,onShow,onTabItemTap,onReachBottom,onPullDownRefresh,onPageScroll } from '@dcloudio/uni-app';
	import dayjs from 'dayjs'
    let { proxy } = getCurrentInstance()
	let obj = reactive({
		dayjs,
		f: {
			"file_id": 0,
			"project_id": "",
			"project_name": "",
			"filepath": "",
			"filename": [],
			"situation": "",
			"caption": "",
			"location": 0
		},
		showpre: false,
		pres: [],
		preidx: 0,
		syScale: 1,
		roles: []
	})
	
	onLoad((opt)=>{
		console.log('opt',opt);
		obj.f = {
			...obj.f,
			...opt,
			location: Number(opt.location)||0
		}
		let roles = opt.roles?JSON.parse(opt.roles):[];
		if(obj.f.file_id>0){
			obj.roles = roles.length==1?roles:(roles.filter(e=>e.role===opt.role&&e.title===opt.roletitle))
		}else{
			obj.roles = roles
		}
		obj.roles.map(e=>{
			e.localrole = e.role
			e.role = extractVariables(e.role)
			e.forms = e.role.map(ev=>{
				return {
					type: ['day','name','num'].includes(ev)?ev:(ev.includes('|')?'select':'text'),
					show: !['day','name','num'].includes(ev),
					key: ev,
					value: '',
					enums: ev.includes('|')?ev.split('|'):[]
				}
			})
		})
		console.log('obj.roles',obj.roles);
	})
	
	const extractVariables=(str)=>{  
	    // 使用正则表达式匹配 ${} 之间的内容  
	    const regex = /\$\{([^}]+)\}/g;  
	    let matches;  
	    const result = [];  
	  
	    // 使用 exec 方法在字符串中查找所有匹配项  
	    while ((matches = regex.exec(str)) !== null) {  
	        // matches[1] 是捕获组中的内容，即 ${} 之间的内容  
	        result.push(matches[1]);  
	    }  
	  
	    return result;  
	}  
	
	const pre=()=>{
		obj.showpre = check()
		getimgwh(`#preimg_${obj.preidx}`)
	}
	
	const check=()=>{
		let filename = []
		obj.roles.map(e=>{
			let filenames = e.filename?e.filename.split(','):[]
			let rolejson = obj.f.file_id>0?JSON.parse(obj.f.rolejson):{}
			if(!(obj.f.file_id>0)){
				for (let i = 0; i < e.forms.length; i++) {
					const ef = e.forms[i]
					if(!['day','name','num'].includes(ef.key)){
						rolejson[ef.key] = ef.value
					}
				}	
			}
			filenames.map(ee=>{
				let rname = obj.f.file_id>0?obj.f.rname:e.localrole
				if(!(obj.f.file_id>0)){
					if(e.forms&&e.forms.length){
						e.forms.map((ev,i)=>{
							if(ev.type=='day'){
								rname = rname.replace('${day}',dayjs().format('YYYY年MM月DD日'))
							}else if(ev.type=='num'){
								rname = rname.replace('${num}','')
							}else if(ev.type=='name'){
								rname = rname.replace('${name}',obj.f.project_name)
							}else{
								rname = rname.replace('${'+ev.key+'}',ev.value)
							}
						})
					}
				}
				filename.push({
					name: ee,
					rname: rname||'',
					role: e.localrole,
					roletitle: e.title||'',
					rolejson: rolejson
				})	
			})
		})
		obj.f.filename = filename||[]
		if(!obj.f.filename||!obj.f.filename.length){
			proxy.$c.Toast('请上传照片！')
			return false
		}
		obj.pres = obj.f.filename.map(e=>{
			return `${proxy.$c.serverHost}upload/${e.name}`
		})
		obj.preidx = 0
		// if(!obj.f.situation){
		// 	proxy.$c.Toast('请填写施工部位或会议主题或施工杆塔号！')
		// 	return false
		// }
		if(!obj.f.caption){
			proxy.$c.Toast('请填写情况说明！')
			return false
		}
		if(obj.f.location!==0&&obj.f.location!==1){
			proxy.$c.Toast('请选择水印位置！')
			return false
		}
		return true
	}
	
	const next=(i)=>{
		if(i==1){
			if(obj.preidx==obj.pres.length-1){
				obj.preidx = 0
			}else{
				obj.preidx++
			}
		}else{
			if(obj.preidx==0){
				obj.preidx = obj.pres.length-1
			}else{
				obj.preidx--
			}
		}
		getimgwh(`#preimg_${obj.preidx}`)
	}
	
	const getimgwh=(id)=>{
		setTimeout(()=>{
			const query = uni.createSelectorQuery().in(proxy);
			query
			  .select(id)
			  .boundingClientRect((data) => {
				  //1600*1200的最大分辨率图片
				  // if(data.width/data.height>1600/1200){
					 //  obj.syScale = 1/(1600/data.width)
				  // }else{
					 //  obj.syScale = 1/(1200/data.height)
				  // }
			  })
			  .exec();
		},100)
	}
	
	
	const submit=()=>{
		const is = check()
		if(is){
			console.log('obj.roles',obj.roles);
			console.log('obj.f',obj.f);
			// return
			uni.showLoading({title: 'loading...'})
			obj.disabled = true
			proxy.$reQuest.post('mp/project/upfile',obj.f,{token:true}).then(res=>{
				uni.hideLoading()
				obj.disabled = false
				if(res.success){
					proxy.$c.Toast('成功！')
					uni.navigateBack({delta:1})
				}else{
					proxy.$c.Toast(res.err||'失败！')
				}
			}).catch(err=>{
				proxy.$c.Toast(err||'失败！')
				uni.hideLoading()
				obj.disabled = false
			})	
		}
	}
</script>

<style lang="scss" scoped>
.pagebox{
	.label{font-size: 28rpx;}
	.spacebox{
		border-radius: 10rpx;background: #f9f9f9;font-size: 28rpx;
		.spacetitle{font-weight: bold;}
	}
	.inputbox{
		width: 100%;height: 80rpx;border-radius: 10rpx;background: #f0f0f0;font-size: 26rpx;
		input{width: 100%;}
	}
	textarea{
		width: 690rpx;min-height: 200rpx;border-radius: 10rpx;background: #f0f0f0;font-size: 26rpx;padding: 20rpx;box-sizing: border-box;
	}
	.textarea1{min-height: 100rpx;}
	.situations{
		.situation{width: 220rpx;height: 60rpx;border-radius: 10rpx;text-align: center;line-height: 60rpx;font-size: 26rpx;background: #f5f6f6;color: #666;}
		.situationactive{background: #d9ebff;color: #4293f0;}
	}
	.locations{
		.loca{width: 330rpx;height: 60rpx;border-radius: 10rpx;text-align: center;line-height: 60rpx;font-size: 26rpx;background: #f5f6f6;color: #666;}
		.locaactive{background: #d9ebff;color: #4293f0;}
	}
	.linebtn{
		width: 690rpx;height: 80rpx;border-radius: 10rpx;text-align: center;line-height: 80rpx;background: #d9ebff;font-size: 28rpx;color: #4293f0;margin-top: 60rpx;
	}
	.btn{
		width: 690rpx;height: 80rpx;border-radius: 10rpx;text-align: center;line-height: 80rpx;background: #4293f0;font-size: 28rpx;color: #fff;
	}
	
	.prebox{
		position: fixed;width: 100vw;height: 100vh;background: rgba(0,0,0,0.6);border-radius: 10rpx;padding: 50rpx;box-sizing: border-box;z-index: 99999999;
		left: 0;top: 0;
		.imgbox{
			width: 100%;max-height: 80vh;background: #rgba(0,0,0,0);.img{width: 100%;}
			.img{
				position: relative;overflow: hidden;
				.shuiyin{
					position: absolute;bottom: 0;background: rgba(255,255,255,0.6);border: solid 4rpx #000;box-sizing: border-box;
					max-width: 1600px;font-size: 24rpx;font-weight: bold;
					.textline{text-decoration: underline;}
				}
				.pos0{left: 0;transform-origin: left bottom;}
				.pos1{right: 0;transform-origin: right bottom;}
			}
		}
		.minibtn{flex: 1;height: 60rpx;border-radius: 10rpx;text-align: center;line-height: 60rpx;background: #d9ebff;font-size: 26rpx;color: #4293f0;}
		.minibtn1{flex: 1;height: 60rpx;border-radius: 10rpx;text-align: center;line-height: 60rpx;background: #f5f6f6;font-size: 26rpx;color: #666;}
	}
}
</style>
